package com.backstage.userModule.service.impl;

import com.backstage.userModule.pojo.User;
import com.backstage.userModule.mapper.UserMapper;
import com.backstage.userModule.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 移动端用户表 服务实现类
 * </p>
 *
 * @author liu-xiang
 * @since 2022-12-13
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
  @Autowired
  private UserMapper userMapper;

  @Override
  public List<User> list(String name, String phone, Integer page, Integer size) {
    Page<User> userPage = new Page<>(page, size);
    QueryWrapper<User> wrapper = new QueryWrapper<>();
    if (name != null)
      wrapper.like("username", name.replace(" ", "")).or().like("nickName", name);
    if (phone != null)
      wrapper.like("phone", phone.replace(" ", ""));
    userMapper.selectPage(userPage, wrapper);
    return userPage.getRecords();
  }

  @Override
  public boolean removeByUid(String uid) {
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("userNum", uid);
    return userMapper.delete(wrapper) > 0;
  }

  @Override
  public boolean updateExists(User user) {
    //更新工具
    UpdateWrapper<User> wrapper = new UpdateWrapper<>();
    wrapper.eq("userNum",user.getUserNum());
    //反射设置更新字段
//    Class userClass = user.getClass();
//    Field[] fields = userClass.getDeclaredFields();
//    Arrays.stream(fields).forEach(field -> {
//      //当属性不为空且非静态时更新
//      if (ObjectUtils.isEmpty(field) && !Modifier.isStatic(field.getModifiers()) && !field.getName().equals("userNum")) {
//        try {
//          wrapper.set(field.getName(), field.get(user));
//        } catch (IllegalAccessException e) {
//          e.printStackTrace();
//        }
//      }
//    });
    return userMapper.update(user,wrapper)>0;
  }
}
